<template>
  <div class="main">
    <!-- 面包屑 -->
    <Top name1='用户管理' name2="用户列表"></Top>
    <!-- 按钮 -->
   <div class="btns">
    <input class="inp" @input="userSer(strs)" v-model.trim="strs" placeholder="请输入用户名字 或 id" type="text">
    <el-button class="but" icon="el-icon-search" @click="troll"></el-button> 
    <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
    <el-button type="primary" @click="logins" class="chongzhi">重置</el-button>
  </div>
  <!-- 表格 -->
    <table>
      <tr>
        <th></th>       
        <th>姓名</th>
        <!-- <th>创建时间</th> -->
        <th>邮箱</th>
        <th>电话</th>
        <th>角色</th>
        <th>在线状态</th>
        <th>操作</th>
      </tr>
      <tr v-for="(ele,ind) in users" :key="ele.id">
        <td style="width:50px;height:50px">{{ ++ind }}</td> 
        <td style="width:100px">{{ ele.username }}</td>
        <!-- <td style="width:220px">{{ time(ele.create_time) }}</td> -->
        <td style="width:100px">{{ele.email}}</td>
        <td style="width:100px">{{ ele.mobile }}</td>
        <td style="width:100px">{{ ele.role_name }}</td>
        <td style="width:80px">
            <el-switch 
                  v-model="ele.mg_state"
                  @change="userState(ele.id,ele.mg_state)"
                  active-color="rgb(50,155,255)"
                  inactive-color="rgb(224,224,224)"
                  >
          </el-switch>
         </td>
         <td style="width:100px">
          <el-tooltip class="item" effect="light" content="修改用户" placement="top">
            <el-button class="sm" type="primary"  @click="reset(ele.id)" icon="el-icon-edit"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" content="删除用户" placement="top">
            <el-button class="sm" type="danger" @click="deldisplay = true,delId = ele.id" icon="el-icon-delete"></el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="light" content='修改角色' placement="top">
          <el-button class="sm" type="warning" icon="el-icon-setting"></el-button></el-tooltip>
        </td>
      </tr>
    </table>
    <!-- 底部页数 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagnum"
        :page-sizes="[5,10]"
        :page-size=pages
        layout="total, sizes, prev, pager, next, jumper"
        :total=usersNum>
      </el-pagination>
    </div>
  <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="400px"
      >
      <el-form  :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="100px" class="demo-dynamic">
        <!-- 用户名 -->
        <el-form-item
          prop="username"
          label="用户名"
          :rules="[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { required: true, message: '请输入正确的用户名', trigger: ['blur', 'change'] }
          ]"
        >
          <el-input style="width:200px" v-model="dynamicValidateForm.username"></el-input>
        </el-form-item>
          <!-- 密码 -->
          <el-form-item
          prop="password"
          label="密码"
          :rules="[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { pattern:/\w{6,16}$/, message: '密码格式错误' }
          ]"
        >
          <el-input style="width:200px"  v-model="dynamicValidateForm.password"></el-input>
        </el-form-item>
        <!-- 手机 -->
        <el-form-item
          prop="mobile"
          label="手机号"
          :rules="[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { required: true, message: '请输入正确的手机号', trigger: ['blur', 'change'] },
            { pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
          ]"
        >
          <el-input style="width:200px" v-model="dynamicValidateForm.mobile"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]"
        >
          <el-input style="width:200px" v-model="dynamicValidateForm.email"></el-input>
      </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAjax">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改信息"
      :visible.sync="xgdisplay"
      width="400px"
      >
      <el-form  :model="resetForm" ref="resetForm" label-width="100px" class="demo-dynamic">
        <!-- 用户名 -->
        <el-form-item
          prop="username"
          label="用户名"
        >
          <el-input style="width:200px" disabled v-model="resetForm.username"></el-input>
        </el-form-item>
        <el-form-item
          prop="mobile"
          label="手机号"
          :rules="[
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { required: true, message: '请输入正确的手机号', trigger: ['blur', 'change'] },
            { pattern: /^1[34578]\d{9}$/, message: '目前只支持中国大陆的手机号码' }
          ]"
        >
          <el-input style="width:200px" v-model="resetForm.mobile"></el-input>
        </el-form-item>
        <!-- 邮箱 -->
        <el-form-item
          prop="email"
          label="邮箱"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]"
        >
          <el-input style="width:200px" v-model="resetForm.email"></el-input>
      </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="xgdisplay = false">取 消</el-button>
        <el-button type="primary" @click="resetAjaxbtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除确认框 -->
    <el-dialog
      title="注意"
      :visible.sync="deldisplay"
      width="400px"
      >
      <span>此操作会永久删除用户,是否继续删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deldisplay = false">取 消</el-button>
        <el-button type="primary" @click="relbtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Top from '../../components/top.vue'
import { trollAjax,addAjax,delAjax,userAjax,staAjax,resetAjax } from '../../api/user'


  export default {
    components:{
      Top,
    },
    computed:{
      // 时间戳转日期的计算属性
      time(){
        // 个位数补0
        function addZero(num){
          if(parseInt(num) < 10){
          num = '0'+num
          }
          return num
        }
        // 时间戳转日期 传参用过函数返回
        return function(i){
          if(i){
            var oDate = new Date(i),
            oYear = oDate.getFullYear(),
            oMonth = oDate.getMonth()+1,
            oDay = oDate.getDate(),
            oHour = oDate.getHours(),
            oMin = oDate.getMinutes(),
            oSen = oDate.getSeconds(),
            oTime = oYear +'-'+ addZero(oMonth) +'-'+ addZero(oDay) +' '+ addZero(oHour) +':'+
            addZero(oMin) +':'+addZero(oSen);
            return oTime
          }else{
            return "未知参数"
          }
           
        }
      }
    },
    data () {
      return {
        currentPage1: 1,
        currentPage2: 2,
        currentPage3: 3,
        currentPage4: 4,
        username:"",
        password:"",
        mobile:"",
        email:"",
        // 用户数据
        users:[],
        // 从sessionStrage中拿数据总数
        usersNum:JSON.parse(window.sessionStorage.getItem('usersNum')),
        // 输入的要搜索的id
        strs:"",
        // 从sessionStrage中拿上次设置的单页条数
        pages:JSON.parse(window.sessionStorage.getItem('page')),
        sta:false,
        // 对话框状态
        dialogVisible:false,
        dynamicValidateForm: {
          domains: [{
            value: ''
          }],
          username:"",
          password:"",
          mobile:"",
          email:"",
        },
        // 修改对话框
        xgdisplay:false,
        resetForm: {
          domains: [{
            value: ''
          }],
          id:"",
          mobile:"",
          username:"",
          email:"",
        },
        // 删除框
        deldisplay : false,
        delId:0,
        // 当前页数
        pagnum:0,
        usersNum:0
      };
      
    },
    // 加载页面请求数据
    async created(){
      if(!window.sessionStorage.getItem('page')){
          this.pages = 10
      }
      let res = await userAjax({
          pagenum:1,
          pagesize:this.pages
      })
      this.usersNum = res.data.data.total
      this.users = res.data.data.users
      
    },
    methods:{
      // 设置每页多少条 并重新请求数据渲染到页面
      async handleSizeChange(val) {
        this.pages = val
        //设置每页条数存到localStronge 刷新后保持展示上次选择的条数
        window.sessionStorage.setItem('page',JSON.stringify(val));
        let res = await userAjax({
          pagenum:1,
          pagesize:this.pages
        })
        this.users = res.data.data.users
      },
      // 点击第几页 重新请求并渲染到页面
      async handleCurrentChange(val) {
        // console.log(val);
        this.pagnum = val
        let res = await userAjax({
          pagenum:val,
          pagesize:this.pages
        })
  
        this.users = res.data.data.users
      },
      // 搜索用户
      async troll(){
        if(this.strs!=""){
          const res = await trollAjax({
            id:this.strs
          })
          // 查到的用户渲染到页面
          this.users = []
          this.users.push(res.data.data)
          this.strs = ""
          // 重置数据条数
          this.usersNum = this.users.length
        }
      },
      //删除单个
      async relbtn(){
          const res =  await delAjax({
          id:this.delId
        })
       if(res.data.meta.status==200){
        this.deldisplay = false
        this.delId = 0
          this.$message({
            message: '删除成功',
            type:'success'
          })
          let res = await userAjax({
            pagenum:1,
            pagesize:this.pages
          })
          this.users = res.data.data.users
          // 重置数据总数
          if(this.pages==10){
            window.sessionStorage.setItem('usersNum',JSON.stringify(res.data.data.users.length));
          }
        }else{
          this.$message({
            message: res.data.meta.msg,
            type:'error'
          })
        }
      },
      // 改变用户状态
      async userState(id,sta){
        const res = await staAjax({
          id:id,
          sta:sta
        })
        if(res.data.meta.status!=200){
          this.$message({
            message: '改变状态失败！',
            type:'error'
          })
          this.$router.go(0);
        }
      },
      // 根据名字搜索
      async userSer(query){
        if(query!=''){
          let res = await userAjax({
            query,
            pagenum:1,
            pagesize:this.pages
          })
          this.users = res.data.data.users
        }else if(query==""){
          let res = await userAjax({
            pagenum:1,
            pagesize:this.pages
          })
          this.users = res.data.data.users
        }
      },
      // 搜索重置
      logins(){
        this.$router.go(0);
      },
      // 添加用户 对话框操作
      addAjax(){
        // this.dialogVisible = false
        this.$refs.dynamicValidateForm.validate(async(validate)=>{
          if(!validate){
            this.dialogVisible = false
            return this.$message({
              message:'添加失败，信息填写错误',
              type:'error'
            })
          }else{
            const res = await addAjax({
              username:this.dynamicValidateForm.username,
              password:this.dynamicValidateForm.password,
              mobile:   this.dynamicValidateForm.mobile,
              email:    this.dynamicValidateForm.email,
            })
            if(res.data.meta.status==201){
              let Newres = await userAjax({
                pagenum:1,
                pagesize:this.pages
              })
              this.users = Newres.data.data.users
              this.dialogVisible = false
              this.$refs.dynamicValidateForm.resetFields();
              return this.$message({
                message:'添加成功',
                type:'success'
              })
            }else{
              return this.$message({
                message:'添加失败',
                type:'error'
              })
            }
          }
        })
      },
      // 修改展示对话框
      async reset(id){
          const res = await trollAjax({
            id:id
          })
          if(res.data.meta.status==200){
            this.xgdisplay = true
            this.resetForm.mobile = res.data.data.mobile
            this.resetForm.email = res.data.data.email
            this.resetForm.id = res.data.data.id
            this.resetForm.username = res.data.data.username
          }else{
            return this.$message({
                message:'获取失败',
                type:'error'
          })
          }
        },
      // 修改ajax请求
      async resetAjaxbtn(){
        if(this.resetForm.mobile&&this.resetForm.email){
          console.log(this.resetForm.mobile,this.resetForm.email);
          let res =  await resetAjax({
          mobile:this.resetForm.mobile,
          email :this.resetForm.email,
          id    :this.resetForm.id
        }) 
        // console.log(res);
        if(res.data.meta.status!=200){
          this.xgdisplay = false
          return this.$message({
                message:'更新失败',
                type:'error'
          })
        }else{
          this.xgdisplay = false
          let res = await userAjax({
              pagenum:1,
              pagesize:this.pages
          })
          this.users = res.data.data.users
          this.$refs.resetForm.resetFields()
          return this.$message({
                message:'更新成功',
                type:'success'
          })
        }
        }else{
          this.xgdisplay = false
          return this.$message({
                message:'更新失败',
                type:'error'
          })
        }
      
      }
    }
  }
</script>
<style lang='scss' scoped>
.chongzhi{
  background-color: #f5f6f8;
  color: rgb(63, 65, 67);
  border: #f5f6f8;
  letter-spacing: 15px;
  text-indent: 5px;
  padding-right: 10px;
  text-align: center;
}
.main{
  padding:30px 0 0 10%;
  .btns{
    display: flex;
  }
  table{
    margin-top: 15px;
  width: 1100px;
  border-collapse: collapse;
  tr{
    height: 40px;
  }
  tr:nth-of-type(even){
    background-color: #fafafa;
  }
  td{
    padding: 5px 10px;
  }
  }
  table,th,td{
    text-align: center;
    border: 1px solid #DCDFE6;
  }
  .inp{
    width: 200px;
    height: 38px;
    border: 1px solid #DCDFE6;
    border-radius: 4px 0 0 4px;
    border-right: 0px;
    text-indent: 1em;
  }
  .but{
    border-radius: 0 10px 10px 0;
  }
  .sm{
    width: 20px;
    height: 20px;
    padding: 2px;
  }
  .add{
    overflow: hidden;
  
    h3{
      background-color: #f5f6f8;
      width: 640px!important;
      height: 50px;
      line-height: 50px;
      margin-top: -40px;
      margin-bottom: 40px;
      margin-left: -50px;
      text-indent: 3em;
      font-size: 18px;
      font-weight: 200;
    }
    position: relative;
    .guan{
      position: absolute;
      top: 0;
      height: 50px;
      width: 60px;
      right: 0px;
      border-radius:0 20px 0 0 ;
    }
    .addbtn{
      display: flex;
      justify-content:space-evenly;
      align-content: center;
    }
    background: white;
    padding: 20px;
    border: 1px solid #DCDFE6;
    padding-top: 40px;
    border-radius: 20px;
    width: 600px;
    height: 260px;
    position: absolute;
    top: 50%;
    margin-left: -300px;
    margin-top: -150px;
    left: 50%;
    .inps{
      width: 200px;
      margin: 10px 20px 20px 0px;
      height: 38px;
      border: 1px solid #DCDFE6;
      border-radius: 4px;
      text-indent: 1em;
    }
    padding-left: 50px;
  }
  .no{
    display: none;
  }
  .block{
    display: flex;
    margin-top: 20px;
    width: 1100px;
    justify-content: center;
  }
  .bu{
    background-color: #DCDFE6;
    border: 1px solid #DCDFE6;
  }
}

</style>